package com.foreveross.mofang.datapersistence.infra.utils;

import java.io.IOException;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * hbase工具类，主要用来对建立与hbase的连接和连接池的管理
 * 
 * @author fb
 */
public class HbaseManagerUtil {

	private static final Logger logger = LoggerFactory.getLogger(HbaseManagerUtil.class);

	private volatile static HbaseManagerUtil Instance;

	private Configuration configuration;

	private HBaseAdmin hBaseAdmin;

	private HConnection connection;

	private HbaseManagerUtil() {
		configuration = HBaseConfiguration.create();

		try {
			connection = HConnectionManager.createConnection(configuration);
			hBaseAdmin = new HBaseAdmin(configuration);
		} catch (Exception e) {
			logger.error("创建HBaseAdmin时异常，异常堆栈：", e);
		}
	}

	public static HbaseManagerUtil getInstance() {
		if (Instance == null) {
			synchronized (HbaseManagerUtil.class) {
				if (Instance == null) {
					Instance = new HbaseManagerUtil();
				}
			}
		}

		return Instance;
	}

	public HTableInterface getHtable(String tableName) throws IOException {
		return connection.getTable(tableName);
	}

	public synchronized void createTable(String tableName, List<String> familys)
			throws Exception {
		if (hBaseAdmin.tableExists(tableName)) {
			logger.info("[{}]表己存在,系统将跳过此表!", tableName);
		} else {
			HTableDescriptor tableDescriptor = new HTableDescriptor(
					TableName.valueOf(tableName));

			for (String string : familys) {
				tableDescriptor.addFamily(new HColumnDescriptor(string));
			}
			
			hBaseAdmin.createTable(tableDescriptor);
		}
	}

	public synchronized void deleteTable(String tableName) throws Exception {
		hBaseAdmin.disableTable(tableName);
		hBaseAdmin.deleteTable(tableName);
		logger.info("删除hbase表[{}]成功!", tableName);
	}

	public synchronized void releaseHTable(String tableName) throws IOException {
		HTableInterface t = getHtable(tableName);

		if (t != null) {
			t.close();
		}
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public HBaseAdmin gethBaseAdmin() {
		return hBaseAdmin;
	}

	public void sethBaseAdmin(HBaseAdmin hBaseAdmin) {
		this.hBaseAdmin = hBaseAdmin;
	}

}
